#pragma once
#include<iostream>
#include<thread>
#include<pthread.h>
#include<signal.h>
#include"TcpServer.hpp"
#include"log.hpp"
#include"Task.hpp"
#include"Threadpool.hpp"
#define PORT 8081

//你好
class HttpServer
{
    public:
        HttpServer(int port = PORT)
            :_port(port),_tcp_server(nullptr),_stop(false)
        {}
        void Init()
        {
            //忽略sigpipe这个信号,避免写入出错服务器挂掉
            signal(SIGPIPE,SIG_IGN);
            cout << "执行thread初始化任务" << endl;
            _thread_pool = Threadpool::GetThreadPool();
            cout << "执行tcp初始化任务" << endl;
            _tcp_server = TcpServer::getTcpserver(_port);
        }

        void Loop()
        {
            //开始监听
            LOG(INFO,"循环开始");
            int listen_sock = _tcp_server->retsock();
            while(!_stop)
            {
                //cout << "----------" << endl;
                sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(listen_sock,(sockaddr*)&peer,&len);
                LOG(INFO,"有一个新连接连入服务器");
                if(sock >= 0)
                {
                   
                    // thread t1(CallBack::HandlerRequest,sock);
                    // t1.detach(); 

                    
                    Task t(sock);
                    _thread_pool->PushTask(t);
                    
                }
            }
            
        }
        // int thread_han(int sock)
        // {
        //     Protocol::HandlerRequest2(sock);
        //     return 0;
        // }

    private:
        int _port;
        TcpServer* _tcp_server;
        bool _stop;
        Threadpool* _thread_pool;//设置线程池
};
